# coding: utf-8
from django.db import models
from django.contrib.auth.models import User
#from django_extensions.db.fields import *
from resources.models import Resource
from taxonomy.models import Category, Tag
import uuid

JOIN_CHOICES = (
    ( '1', '需要审核' ),
    ( '0', '不需要审核' ),
)
# An abstract base class that should be inherited by every model which contains
# an unique GUID
#class BaseId( models.Model ):
#   id = UUIDField( max_length = 36, primary_key = True, default = uuid.uuid1() )
#   class Meta:
#       abstract = True

class Theme( models.Model ):
    name = models.CharField( max_length = 100, verbose_name = '主题小组名称' )
    people = models.TextField( null = True, verbose_name = '目标人群' )
    intro = models.TextField( null = True, verbose_name = '导入' )
    objective = models.TextField( null = True, verbose_name = '学习目标' )
    strategy = models.TextField( null = True, verbose_name = '学习策略指导' )
    content = models.TextField( null = True, verbose_name = '学习内容' )
    member_count =  models.PositiveIntegerField( default = 1 )
    point = models.IntegerField( default = 0, verbose_name = '积分' )
    pic = models.ImageField( upload_to = 'photos/', null = True, blank = True,
    verbose_name = '主题小组照片' )
    notice = models.TextField( null = True, verbose_name = '小组公告' )
    join = models.CharField( max_length = 1, choices = JOIN_CHOICES,
    verbose_name = '加入方式' )
    user = models.ForeignKey( User, verbose_name = '创建人' )
    users = models.ManyToManyField( User, related_name = 'User_related',
    verbose_name = '小组成员' )
    resources = models.ManyToManyField( Resource, blank = True, verbose_name = '资源' )
    # FIXME
    categories = models.ManyToManyField( Category, blank = True, verbose_name = '分类' )
    tags = models.ManyToManyField( Tag, blank = True, verbose_name = '标签' )

    @models.permalink
    def get_absolute_url( self ):
        return ( 'theme_detail', [str(self.id)] )

    def __unicode__( self ):
        return self.name



class Achievement( models.Model ):
    user = models.ForeignKey( User, verbose_name = 'created_by' )
    theme = models.ForeignKey( Theme, verbose_name = 'belong_to' )
    start_time = models.DateField()
    end_time = models.DateField()
    content = models.TextField( null = True )
    notes = models.TextField( null = True )
    point = models.PositiveIntegerField()
    resources = models.ManyToManyField( Resource )

class Attachment( models.Model ):
    achievement = models.ForeignKey( Achievement, verbose_name = 'belong_to' )
    url = models.FileField( upload_to = 'media/' )
    description = models.TextField( null = True )

class Topic(models.Model):
    theme = models.ForeignKey( Theme, related_name = 'topics', verbose_name = '所属主题' )
    name = models.CharField( max_length = 255, verbose_name = '标题')
    created = models.DateTimeField( auto_now_add = True, verbose_name = '发布时间' )
    updated = models.DateTimeField( null = True, verbose_name = '更新时间' )
    user = models.ForeignKey( User, verbose_name = '发布人' )
    post_count = models.IntegerField( blank=True, default = 0, verbose_name = '回应数' )

    class Meta:
        ordering = ['-updated']

    def __unicode__(self):
        return self.name

    @property
    def head(self):
        try:
            return self.posts.select_related().order_by('created')[0]
        except IndexError:
            return None

    @property
    def reply_count(self):
        return self.post_count - 1

    @models.permalink
    def get_absolute_url(self):
        return ('topic', [self.id])

class Post( models.Model ):
    topic = models.ForeignKey( Topic, related_name = 'posts', verbose_name = '所属话题')
    user = models.ForeignKey( User, related_name='posts', verbose_name = '发布人' )
    created = models.DateTimeField( auto_now_add = True, verbose_name = '发布时间' )
    content = models.TextField( verbose_name = '内容' )
    class Meta:
        ordering = ['created']
        get_latest_by = 'created'

    def save(self, *args, **kwargs):
        super(Post, self).save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        self_id = self.id
        head_post_id = self.topic.posts.order_by('created')[0].id
        theme = self.topic.theme
        topic = self.topic
        self.last_topic_post.clear()
        self.last_forum_post.clear()
        super(Post, self).delete(*args, **kwargs)
        #if post was last in topic - remove topic
        if self_id == head_post_id:
            topic.delete()
        else:
            try:
                topic.last_post = Post.objects.filter(topic=topic).latest()
            except Post.DoesNotExist:
                topic.last_post = None
            topic.post_count = Post.objects.filter(topic=topic).count()
            topic.save()
        try:
            forum.last_post = Post.objects.filter(topic__forum=forum).latest()
        except Post.DoesNotExist:
            forum.last_post = None

    @models.permalink
    def get_absolute_url( self ):
        return ('post', [self.id])

class AchievementComment( models.Model ):
    user = models.ForeignKey( User, verbose_name = 'posted_by' )
    post_time = models.DateTimeField()
    content = models.TextField()
    achievement = models.ForeignKey( Achievement )
